package cn.car91.utils;

import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import cn.car91.view.HerilyAlertDialog;

public class MobileOperationUtil {
  static Pattern phonePattern = Pattern
      .compile("1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,8}");
  
  /**
   * 拨号
   * @param number 电话号码可为null
   */
  public static void callPhone(final Context context,String number) {
    final Intent intent = new Intent();
    if (RegexUtil.isNotNull(number)) {
      try {
        String[] numbers = number.split("\\s+");
        intent.setAction(Intent.ACTION_CALL);
        if (numbers.length == 1) {
          Matcher matcher = phonePattern.matcher(numbers[0]);
          if (matcher.find()) {
            intent.setData(Uri.parse("tel:" + matcher.group()));
          } else {
            intent.setAction(Intent.ACTION_DIAL);
          }
          context.startActivity(intent);
        } else if (numbers.length > 1) {
          final List<String> allNumber = Arrays.asList(numbers);
          new HerilyAlertDialog.Builder(context)
              .setTitle("服务热线")
              .setItems(numbers, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                  try {
                    Matcher matcher = phonePattern.matcher(allNumber
                        .get(arg1));
                    if (matcher.find()) {
                      intent.setData(Uri.parse("tel:" + matcher.group()));
                    } else {
                      intent.setAction(Intent.ACTION_DIAL);
                    }
                  } catch (Exception e) {
                    intent.setAction(Intent.ACTION_DIAL);
                  }
                  context.startActivity(intent);
                }
              }).setNegativeButton("取消", null).create().show();
        }
      } catch (Exception e) {
        intent.setAction(Intent.ACTION_DIAL);
        context.startActivity(intent);
      }
    } else {
      intent.setAction(Intent.ACTION_DIAL);
      context.startActivity(intent);
    }
  }
}
